package com.greenantmall.adapter;

import java.text.DecimalFormat;
import java.util.List;

import com.avos.avoscloud.AVUser;
import com.greenantmall.R;
import com.greenantmall.AntHomeApplication;
import com.greenantmall.activity.DetailActivity;
import com.greenantmall.activity.LoginActivity;
import com.greenantmall.bean.Goods;
import com.greenantmall.bean.ShoppingCart;
import com.greenantmall.bean.UIGoods;
import com.greenantmall.service.RetrieveDataAsyn;
import com.greenantmall.service.RetrieveDataListener;
import com.greenantmall.utils.Const;
import com.greenantmall.utils.UtilTools;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class GoodsListAdapterForItem1 extends BaseAdapter {
	private Context mContext;
	private LayoutInflater mLayoutInflater;
	private DecimalFormat mDecimalFormat;
	
	private List<UIGoods> mDataList;
	private List<ShoppingCart> mShoppingCartList;
	
	public GoodsListAdapterForItem1(Context context, List<UIGoods> dataList, List<ShoppingCart> shoppingCartList) {
		mContext = context;
		mLayoutInflater = LayoutInflater.from(mContext);
		mDataList = dataList;
		mShoppingCartList = shoppingCartList;
		mDecimalFormat = new DecimalFormat("#########.##");
	}

	@Override
	public int getCount() {
		if(mDataList != null) {
			return mDataList.size();
		}
		return 0;
	}

	@Override
	public Object getItem(int arg0) {
		return arg0;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View child = convertView;
		ViewHolder holder = null;
		if(child == null) {
			child = mLayoutInflater.inflate(R.layout.goods_list_for_item1_item, null);
			holder = new ViewHolder(child);
			child.setTag(holder);
		}
		else {
			holder = (ViewHolder)child.getTag();
		}
		
		holder.setPosition(position);
		
		UIGoods goods = mDataList.get(position);
		ImageLoader.getInstance().displayImage(goods.getPicUrl(), holder.getIvPic(),AntHomeApplication.imageDisplayOptions);
		holder.getTvDes().setText(goods.getDescroptionAndSpecs());
		double marketPrice = goods.getPriceBeforeDiscount();
		marketPrice = (marketPrice<0 ? 0 : marketPrice);
		holder.getTvMarketPrice().getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
		holder.getTvMarketPrice().setText(String.valueOf(marketPrice));
		holder.getTvPrice().setText(mDecimalFormat.format(goods.getPriceAfterDiscount()));
		holder.getTvUnit().setText(" / " + goods.getUnit());
		int showTag = goods.getShowTag();
		if(showTag == 1) {
			holder.getShowTag().setVisibility(View.VISIBLE);
			holder.getShowTag().setBackgroundResource(R.drawable.show_tag_promotion);
		}
		else if(showTag == 2) {
			holder.getShowTag().setVisibility(View.VISIBLE);
			holder.getShowTag().setBackgroundResource(R.drawable.show_tag_hotsale);
		}
		else {
			holder.getShowTag().setVisibility(View.INVISIBLE);
		}
		
		holder.getTvInBasketNum().setVisibility(View.GONE);
		holder.getTvCountUnit().setVisibility(View.GONE);
		holder.getBtnSubtract().setVisibility(View.GONE);
		if(mShoppingCartList != null) {
			for(ShoppingCart sc : mShoppingCartList) {
				String goodsId = sc.getGoodsid();
				double quantity = sc.getQuantity();
				if(goodsId != null && goodsId.equals(goods.getObjectId())) {
					holder.getTvInBasketNum().setVisibility(View.VISIBLE);
					holder.getTvCountUnit().setVisibility(View.VISIBLE);
					holder.getBtnSubtract().setVisibility(View.VISIBLE);
					
					if(Math.floor(quantity) - quantity == 0) {
						holder.getTvInBasketNum().setText(String.valueOf((int)quantity));
						holder.getTvCountUnit().setText(String.valueOf((int)quantity));
					}
					else {
						holder.getTvInBasketNum().setText(String.valueOf(quantity));
						holder.getTvCountUnit().setText(String.valueOf(quantity));
					}
					break;
				}
			}
		}
		
		if(showTag == 3 || goods.getStock() <= 0) {
			holder.getShowTagSoldOut().setVisibility(View.VISIBLE);
			holder.getBtnLayout().setVisibility(View.GONE);
		}
		else {
			holder.getShowTagSoldOut().setVisibility(View.GONE);
			holder.getBtnLayout().setVisibility(View.VISIBLE);
		}
		
		return child;
	}
	
	private class ViewHolder implements OnClickListener {
		private View mContentView;
		private ImageView mIvPic;
		private View mShowTag;
		private View mShowTagSoldOut;
		private TextView mTvDes;
		private TextView mTvMarketPrice;
		private TextView mTvPrice;
		private TextView mTvUnit;
		private TextView mTvInBasketNum;
		private TextView mTvCount;
		private Button mBtnSubtract;
        private Button mBtnAdd;
        private View mBtnLayout;
        private View mViewForClick;
        
        private int mPosition;
        
        private boolean isAddedOrSubtracted = false;
		
		public ViewHolder(View contentView) {
			mContentView = contentView;
			getBtnSubtract();
            getBtnAdd();
            mViewForClick = mContentView.findViewById(R.id.goods_list_item_for_click);
            mViewForClick.setOnClickListener(this);
		}
		
		public void setPosition(int position)
        {
            this.mPosition = position;
        }
		
		public TextView getTvInBasketNum() {
			if(mTvInBasketNum == null) {
				mTvInBasketNum = (TextView)mContentView.findViewById(R.id.goods_list_item_in_basket_num);
			}
			return mTvInBasketNum;
		}
		
		public View getShowTag() {
			if(mShowTag == null) {
				mShowTag = mContentView.findViewById(R.id.goods_list_item_pic_show_tag);
			}
			return mShowTag;
		}
		
		public View getShowTagSoldOut() {
			if(mShowTagSoldOut == null) {
				mShowTagSoldOut = mContentView.findViewById(R.id.goods_list_item_pic_show_tag_sold_out);
			}
			return mShowTagSoldOut;
		}

		public ImageView getIvPic() {
			if(mIvPic == null) {
				mIvPic = (ImageView)mContentView.findViewById(R.id.goods_list_item_pic);
			}
			return mIvPic;
		}

		public TextView getTvDes() {
			if(mTvDes == null) {
				mTvDes = (TextView)mContentView.findViewById(R.id.goods_list_item_des);
			}
			return mTvDes;
		}
		
		public TextView getTvMarketPrice() {
			if(mTvMarketPrice == null) {
				mTvMarketPrice = (TextView)mContentView.findViewById(R.id.goods_list_item_market_price_right);
			}
			return mTvMarketPrice;
		}

		public TextView getTvPrice() {
			if(mTvPrice == null) {
				mTvPrice = (TextView)mContentView.findViewById(R.id.goods_list_item_price);
			}
			return mTvPrice;
		}

		public TextView getTvUnit() {
			if(mTvUnit == null) {
				mTvUnit = (TextView)mContentView.findViewById(R.id.goods_list_item_unit);
			}
			return mTvUnit;
		}
		
		public TextView getTvCountUnit()
        {
            if (mTvCount == null)
            {
                mTvCount =
                    (TextView) mContentView.findViewById(R.id.goods_list_item_count);
            }
            return mTvCount;
        }

        public Button getBtnSubtract()
        {
            if (mBtnSubtract == null)
            {
                mBtnSubtract = (Button) mContentView.findViewById(R.id.goods_list_item_subtract);
                mBtnSubtract.setOnClickListener(this);
            }
            return mBtnSubtract;
        }
        
        public Button getBtnAdd()
        {
            if (mBtnAdd == null)
            {
                mBtnAdd = (Button) mContentView.findViewById(R.id.goods_list_item_add);
                mBtnAdd.setOnClickListener(this);
            }
            return mBtnAdd;
        }
        
        public View getBtnLayout()
        {
            if (mBtnLayout == null)
            {
            	mBtnLayout = mContentView.findViewById(R.id.goods_list_item_price_and_count_ll);
            	mBtnLayout.setOnClickListener(this);
            }
            return mBtnLayout;
        }
        
        @Override
        public void onClick(View v)
        {
        	if(v.equals(mViewForClick)) {
        		UIGoods uiGoods = mDataList.get(mPosition);
        		Intent intent = new Intent(mContext, DetailActivity.class);
        		intent.putExtra(DetailActivity.KEY_DETAIL_OBJECTID, uiGoods.getObjectId());
        		mContext.startActivity(intent); 
        	}
        	else if (v.equals(mBtnSubtract))
            {
            	Log.d("CEXX", "ShoppingCartListAdapter ---> onClick ---> mBtnSubtract");
            	if(isAddedOrSubtracted){
            		return;
            	}
            	isAddedOrSubtracted = true;
            	
            	if(mShoppingCartList != null) {
            		ShoppingCart shoppingCart = null;
            		final UIGoods goods = mDataList.get(mPosition);
        			for(ShoppingCart sc : mShoppingCartList) {
        				Goods scGoods = sc.getGoods();
        				if(goods.getObjectId().equals(scGoods.getObjectId())) {
        					shoppingCart = sc;
        					break;
        				}
        			}
        			
        			if(shoppingCart == null) {
        				isAddedOrSubtracted = false;
        				return;
        			}
        			
        			try {
        				final ShoppingCart uiShoppingCart = shoppingCart;
                        final Goods uiGoods = uiShoppingCart.getGoods();
                        double quantity = uiShoppingCart.getQuantity();
                        double step = uiGoods.getWeighStep();
                        double price = uiGoods.getRealPrice();
                        final String stepUnit = uiGoods.getWeighUnit();
                        Log.d("CEXX", "ShoppingCartListAdapter ---> onClick ---> mBtnSubtract ---> step : " + step);
                        
                        if(quantity - step > 0) {
                        	quantity -= step;
                        	uiShoppingCart.setQuantity(quantity);
                        	uiShoppingCart.setCost(price*quantity);
                        	
                        	RetrieveDataAsyn.getInstance().updateShoppingCart(
                        			uiShoppingCart, 
                        			AVUser.getCurrentUser().getObjectId(), 
                        			-1, 
                        			new RetrieveDataListener()
                                {
                                    @Override
                                    public void dataRetrieved(int requestId, Object data)
                                    {
                                    	isAddedOrSubtracted = false;
                                    	
                                    	if(data != null) {
                                        	AntHomeApplication.shoppingMap.put(uiShoppingCart.getGoodsid(), uiShoppingCart);
                                            Intent intent = new Intent(Const.SHOPPING_CART_CHANGED);
                                            mContext.sendBroadcast(intent);
                                    	}
                                    }
                                });
                        }
                        else if(quantity - step == 0) {
                        	RetrieveDataAsyn.getInstance().removeShoppingCart(
                        			uiShoppingCart, 
		    						-1, 
		    						new RetrieveDataListener() {
								@Override
								public void dataRetrieved(int requestId, Object data) {
									isAddedOrSubtracted = false;
									if(data != null) {
										getTvCountUnit().setVisibility(View.GONE);
										getBtnSubtract().setVisibility(View.GONE);
		                                mContext.sendBroadcast(new Intent(Const.SHOPPING_CART_CHANGED));
									}
								}
							});
                        }
                        else {
                        	isAddedOrSubtracted = false;
                        }
                	}
                	catch(Exception e) {
                		isAddedOrSubtracted = false;
                		e.printStackTrace();
                	}
        		}
            }
            else if(v.equals(mBtnAdd))
            {
            	Log.d("CEXX", "ShoppingCartListAdapter ---> onClick ---> mBtnAdd");
            	if(AVUser.getCurrentUser() == null) {
					Intent intent = new Intent(mContext, LoginActivity.class);
					mContext.startActivity(intent);
					return;
				}
            	
            	if(isAddedOrSubtracted){
            		return;
            	}
            	isAddedOrSubtracted = true;
            	
            	if(mShoppingCartList != null) {
            		ShoppingCart shoppingCart = null;
            		final UIGoods goods = mDataList.get(mPosition);
        			for(ShoppingCart sc : mShoppingCartList) {
        				Goods scGoods = sc.getGoods();
        				if(goods.getObjectId().equals(scGoods.getObjectId())) {
        					shoppingCart = sc;
        					break;
        				}
        			}
        			
        			if(shoppingCart == null) {
        				RetrieveDataAsyn.getInstance().addToShoppingCart(
        						AVUser.getCurrentUser().getObjectId(),
    							AntHomeApplication.sectionNum,
    							UtilTools.uiGoodsToGoods(goods), goods.getStep(), 0,
    							new RetrieveDataListener() {
    								@Override
    								public void dataRetrieved(int requestId, Object data) {
    									isAddedOrSubtracted = false;
    									ShoppingCart shoppingCart = (ShoppingCart) data;
    									if (shoppingCart != null) {
    										AntHomeApplication.shoppingMap.put(goods.getObjectId(), shoppingCart);
    										Intent intent = new Intent(Const.SHOPPING_CART_CHANGED);
    										mContext.sendBroadcast(intent);
    									}
    								}
    							});
        				return;
        			}
        			
        			try {
                        final ShoppingCart uiShoppingCart = shoppingCart;
                        final Goods uiGoods = uiShoppingCart.getGoods();
                        double quantity = uiShoppingCart.getQuantity();
                        double step = uiGoods.getWeighStep();
                        double price = uiGoods.getRealPrice();
                        final String stepUnit = uiGoods.getWeighUnit();
                        double stock = uiGoods.getStock();
                        Log.d("CEXX", "ShoppingCartListAdapter ---> onClick ---> mBtnAdd ---> step : " + step);
                        
                        if(quantity + step <= stock) {
                        	quantity += step;
                        	uiShoppingCart.setQuantity(quantity);
                        	uiShoppingCart.setCost(price*quantity);
                        	
                        	RetrieveDataAsyn.getInstance().updateShoppingCart(
                        			uiShoppingCart, 
                        			AVUser.getCurrentUser().getObjectId(), 
                        			-1, 
                        			new RetrieveDataListener()
                                {
                                    @Override
                                    public void dataRetrieved(int requestId, Object data)
                                    {
                                    	isAddedOrSubtracted = false;
                                    	
                                    	if(data != null) {
                                        	AntHomeApplication.shoppingMap.put(uiShoppingCart.getGoodsid(), uiShoppingCart);
                                            Intent intent = new Intent(Const.SHOPPING_CART_CHANGED);
                                            mContext.sendBroadcast(intent);
                                    	}
                                    }
                                });
                        }
                        else {
                        	isAddedOrSubtracted = false;
                        	UtilTools.showMyToast(mContext, mContext.getResources().getString(R.string.shopping_cart_out_of_stock));
                        }
                	}
                	catch(Exception e) {
                		isAddedOrSubtracted = false;
                		e.printStackTrace();
                	}
        		}
            }
        }
	}

}








